package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import feign.Feign;
import feign.FeignException;
import io.protostuff.ProtostuffIOUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Author: Administrator
 * CreateTime: 2024/9/30
 * Project: heima-leadnews
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    private final IScheduleClient scheduleClient;
    private final WmNewsMapper wmNewsMapper;

    /**
     * 添加任务到延迟队列中
     * @param id
     * @param publishTime
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟队列中——begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);

        log.info("添加任务到延迟队列中——end");
    }

    private final WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 消费延迟队列
     */
    @Override
    @Scheduled(fixedRate = 1000)
    @SneakyThrows
    public void scanNewsByTask() {

//        log.info("文章审核——消费任务执行——begin");

        try {
            ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
            if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
                String json_str = JSON.toJSONString(responseResult.getData());
                Task task = JSON.parseObject(json_str, Task.class);
                byte[] parameters = task.getParameters();
                WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
                log.info("文章审核——开始审核文章——id：{}", wmNews.getId());
                wmNews = wmNewsMapper.selectById(wmNews.getId());
                wmNewsAutoScanService.autoScanWmNews(wmNews);
            }
        }
        catch (FeignException.NotFound e) {
            log.info("没有需要审核的任务");
        }
//        log.info("文章审核——消费任务执行——end");

    }
}
